package com.cskaoyan.service;


import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.MarketPermissionsVo;
import com.cskaoyan.bean.vo.MarketRoleVo;
import com.cskaoyan.bean.vo.PermissionsVo;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author gatsby
 * @since 2022/10/11 23:14
 */
@Service
public class AdminRoleServiceImpl implements AdminRoleService {

    @Autowired
    MarketRoleMapper marketRoleMapper;

    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    /**
     * 查询管理员权限信息的业务逻辑
     *
     * @return com.cskaoyan.bean.common.CommonData<com.cskaoyan.bean.MarketRole>
     * @author gatsby
     * @since 2022/10/11 23:15
     */
    @Override
    public CommonData<MarketRoleVo> queryAdminRole() {
        //int page=0;
        //int limit=0;
        //PageHelper.startPage(page,limit);
        List<MarketRoleVo> marketRoleList = marketRoleMapper.selectRoleMsg();

        PageInfo<MarketRoleVo> pageInfo = new PageInfo<>(marketRoleList);
        int pages = pageInfo.getPages();
        int total = (int) pageInfo.getTotal();
        CommonData<MarketRoleVo> commonData = new CommonData<>();
        commonData.setPages(pages);
        commonData.setTotal(total);
        commonData.setPage(pages);
        commonData.setLimit(total);
        commonData.setList(marketRoleList);
        return commonData;
    }

    /**
     * 查询全部管理员角色信息的业务逻辑
     *
     * @param basePageInfo
     * @param username
     * @return com.cskaoyan.bean.common.BaseRespVo<com.cskaoyan.bean.common.CommonData>
     * @author gatsby
     * @since 2022/10/12 16:48
     */
    @Override
    public BaseRespVo<CommonData> queryAdminLimit(BasePageInfo basePageInfo, String username) {
        //开启分页
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        //创建example
        MarketRoleExample example = new MarketRoleExample();
        example.setDistinct(true);
        //添加排序的条件
        example.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());

        MarketRoleExample.Criteria criteria = example.createCriteria();


        //判断是否需要模糊查询
        if (!StringUtil.isEmpty(username)) {
            criteria.andNameLike("%" + username + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<MarketRole> marketRoleList = marketRoleMapper.selectByExample(example);

        PageInfo<MarketRole> pageInfo = new PageInfo<>(marketRoleList);
        int pages = pageInfo.getPages();
        int total = (int) pageInfo.getTotal();


        CommonData<MarketRole> commonData = new CommonData<>();
        commonData.setPages(pages);
        commonData.setPage(basePageInfo.getPage());
        commonData.setTotal(total);
        commonData.setLimit(basePageInfo.getLimit());
        commonData.setList(marketRoleList);


        return BaseRespVo.ok(commonData, "成功");
    }

    /**
     * 创建管理员权限角色的业务逻辑
     *
     * @param marketRole
     * @return com.cskaoyan.bean.MarketRole
     * @author gatsby
     * @since 2022/10/12 17:21
     */
    @Override
    public MarketRole createRole(MarketRole marketRole) {

        //先判断角色名是否存在
        MarketRoleExample example = new MarketRoleExample();
        example.setDistinct(true);
        MarketRoleExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(marketRole.getName());
        criteria.andDeletedEqualTo(false);
        long count = marketRoleMapper.countByExample(example);
        if (count > 0) {
            //角色名重复
            MarketRole marketRole1 = new MarketRole();
            marketRole1.setId(-1);
            return marketRole1;
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        try {
            Date time = sdf.parse(format);
            marketRole.setAddTime(time);
            marketRole.setUpdateTime(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //插入
        marketRoleMapper.insertSelective(marketRole);
        return marketRole;
    }

    /**
     * 更新管理员角色信息的业务逻辑
     *
     * @param marketRole
     * @return int
     * @author gatsby
     * @since 2022/10/12 18:35
     */
    @Override
    public int updateRole(MarketRole marketRole) {
        MarketRoleExample example = new MarketRoleExample();
        example.setDistinct(true);

        MarketRoleExample.Criteria criteria = example.createCriteria();
        criteria.andIdNotEqualTo(marketRole.getId());
        criteria.andNameEqualTo(marketRole.getName());
        criteria.andDeletedEqualTo(false);
        long count = marketRoleMapper.countByExample(example);
        if (count > 0) {
            //有重复的管理员角色名称
            return -1;
        }
        marketRoleMapper.updateByPrimaryKeySelective(marketRole);

        return 0;
    }

    /**
     * 删除管理员权限角色的业务逻辑
     *
     * @param marketRole 前台返回的管理员信息
     * @return void
     * @author gatsby
     * @since 2022/10/12 18:59
     */
    @Transactional
    @Override
    public void deleteRole(MarketRole marketRole) {
        marketRole.setDeleted(true);
        marketRoleMapper.updateByPrimaryKeySelective(marketRole);
    }

    /**
     * 查询全部权限信息的业务逻辑
     *
     * @param
     * @return
     */
    @Override
    public MarketPermissionsVo queryAllPermissions() {
        //先查询出全部的systemPermission
        //最外层
        List<MarketPermissions> one = marketRoleMapper.selectPermissionsByType(1);
        //第二层
        List<MarketPermissions> two = marketRoleMapper.selectPermissionsByType(2);
        //第三层
        List<MarketPermissions> three = marketRoleMapper.selectPermissionsByType(3);

        //包装每一个two
        List<PermissionsVo> twoList = new ArrayList<>();
        for (MarketPermissions t : two) {
            //创建第三层的单个Permission
            PermissionsVo<MarketPermissions> permissionsVo = new PermissionsVo<>();
            permissionsVo.setId(t.getId());
            permissionsVo.setLabel(t.getLabel());
            //对于每一个two，需要查出two.uid=three.pid的每一条记录
            ArrayList<MarketPermissions> threeForTwo = new ArrayList<>();
            for (MarketPermissions p : three) {
                if (p.getPid() == t.getUid()) {
                    threeForTwo.add(p);
                }
            }
            permissionsVo.setChildren(threeForTwo);
            twoList.add(permissionsVo);
        }

        //包装每一个one
        ArrayList<PermissionsVo> systemPermissions = new ArrayList<>();
        for (MarketPermissions o : one) {
            PermissionsVo<PermissionsVo> permissionsVo = new PermissionsVo<>();
            permissionsVo.setId(o.getId());
            permissionsVo.setLabel(o.getLabel());
            //对于每一个one需要查出one.uid=two.pid
            ArrayList<PermissionsVo> twoForOne = new ArrayList<>();
            for (MarketPermissions p : two) {
                if (p.getPid() == o.getUid()) {
                    for (PermissionsVo t : twoList) {
                        if (t.getId().equals(p.getId())) {
                            twoForOne.add(t);
                        }
                    }
                }
            }
            permissionsVo.setChildren(twoForOne);
            systemPermissions.add(permissionsVo);
        }
        //到这里，得到一个oneList-->改成systemPermissions
        List<String> assignedPermissions = new ArrayList<>();
        for (MarketPermissions th : three) {
            assignedPermissions.add(th.getId());
        }

        MarketPermissionsVo marketPermissionsVo = new MarketPermissionsVo();
        marketPermissionsVo.setSystemPermissions(systemPermissions);
        marketPermissionsVo.setAssignedPermissions(assignedPermissions);


        return marketPermissionsVo;
    }

    /**
     * 给角色授权的业务逻辑
     *
     * @param permissions
     * @param roleId
     * @return void
     * @author gatsby
     * @since 2022/10/13 17:25
     */
    @Override
    public void authPermissions(List<String> permissions, Integer roleId)  {

        //将角色id对应的记录全部删除掉(逻辑删除)
        MarketPermissionExample example = new MarketPermissionExample();
        example.setDistinct(true);
        MarketPermissionExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        criteria.andDeletedEqualTo(false);
        MarketPermission marketPermission1 = new MarketPermission();
        marketPermission1.setDeleted(true);
        marketPermissionMapper.updateByExampleSelective(marketPermission1,example);

        //批量插入
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        Date now=null;
        try {
            now = sdf.parse(format);
        } catch (ParseException e) {
            e.printStackTrace();
        }


        for (String permission : permissions) {
            MarketPermission marketPermission = new MarketPermission();
            marketPermission.setPermission(permission);
            marketPermission.setDeleted(false);
            marketPermission.setUpdateTime(now);
            marketPermission.setAddTime(now);
            marketPermission.setRoleId(roleId);
            //插入
            marketPermissionMapper.insertSelective(marketPermission);
        }




    }
}
